package com.swak.async.persistence.datasource;

import com.swak.annotation.MS;
import com.swak.closable.Closable;
import com.swak.vertx.Vertxs;

import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlConnection;

/**
 * 数据源
 * 
 * @author lifeng
 * @date 2020年10月13日 下午8:54:23
 */
public class DataSource implements Closable {

	/**
	 * 连接池
	 */
	volatile Pool pool;
	MySQLConnectOptions connectOptions;
	PoolOptions poolOptions;

	public DataSource() {
	}

	public DataSource(MySQLConnectOptions connectOptions, PoolOptions poolOptions) {
		this.connectOptions = connectOptions;
		this.poolOptions = poolOptions;
	}

	public void getConnection(MS type, Handler<AsyncResult<SqlConnection>> handler) {
		getPool().getConnection(handler);
	}

	Pool getPool() {
		if (this.pool != null) {
			return this.pool;
		}
		synchronized (this) {
			if (this.pool != null) {
				return this.pool;
			}
			Pool pool = MySQLPool.pool(Vertxs.vertx(), connectOptions, poolOptions);
			this.pool = pool;
		}
		return this.pool;
	}

	@Override
	public void close() {
		try {
			this.pool.close();
		} catch (Exception e) {
		}
	}
}